//
//  MarketScene.cpp
//  SpaceTrader
//
//  Created by Brandon Chastain on 10/26/12.
//  Copyright (c) 2012 The Hex Pistols. All rights reserved.
//
//#include "GuiButton.h"
#include "CommonsScene.h"
#include "GuiButton.h"
#include <sstream>
#include <map>
#include <vector>

CommonsScene::CommonsScene(Market *market) : market(market) { }

CommonsScene::CommonsScene(const CommonsScene &C) : market(C.market) { }

CommonsScene::~CommonsScene(){}

CommonsScene& CommonsScene::operator=(const CommonsScene &C){
    // check for "self assignment" and do nothing in that case
    if (this == &C)
        return *this;
    else {
        delete market;                // free the storage pointed to by Items
        market = C.market;
        return *this;                   // return this IntList
    }
}

/*
 * TODO: rework the updating of button text and state
 * draws the market scene and handles the Market's logic
 * and user input for buying and selling
 */
state_t CommonsScene::draw(SDL_Surface *screen) 
{
    SDL_Event event;
    state_t nextState = MARKET;
	
	std::map<std::string,TradeGood*> *map = market->getItemMap();
	std::vector<std::string> names = market->getItemList();

    GuiButton backButton(0, 0, "", "Back");
	GuiTable infoTable(names.size(), 3, 0, 0, 90, 20, 16);
	//char *info[names->size()*3];
	std::vector<const char*> info;

	//Write TradeGood Names
	for(unsigned int i = 0; i < names.size(); i++) {
		TradeGood* curr = (*map)[names[i]];
		info.push_back(curr->getName());
	}
	
	//Write TradeGood Prices
	for(unsigned int i = 0; i < names.size(); i++) {
		TradeGood* curr = (*map)[names[i]];
		std::ostringstream out;
		out << curr->getBasePrice();
		info.push_back(out.str().c_str());
	}
	
	//Write TradeGood Difference
	for(unsigned int i = 0; i < names.size(); i++) {
		//TradeGood *curr = (*map)[(*names)[i]];
		info.push_back("+0");
	}
	
	const char **contents = &info[0];
    infoTable.setContents(contents);
    infoTable.setCoords(screen->w-infoTable.getTotalWidth()-5, 0);
	
	while (nextState == MARKET) {
        
        while(SDL_PollEvent(&event)) {
            if (event.type==SDL_QUIT) nextState = QUIT;
            if (backButton.handle_input(event) == CLICKED) nextState = PLANET;
		}
        
        SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 0x00, 0x00, 0x00));
		infoTable.show(screen);
        backButton.show(screen);
		
        //Update the screen
		if ( SDL_Flip( screen ) == -1 ) {
			std::cerr << "Error Updating screen." << std::endl;
		}
    }
    
    return nextState;
}